﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using Logging;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;

namespace BackgroundSigner
{
    public class TaskScheduler : ScheduledTaskAgent
    {
        private DateTime _lastRun = DateTime.MinValue;
        private DataBase _dbContext = new Logging.DataBase();

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected async override void OnInvoke(ScheduledTask task)
        {
            if (DateTime.Now - _lastRun < TimeSpan.FromDays(0.5)) return;

            Helper.CreateDb();

            LogMessage("开始签到");

            string message = null;
            try
            {
                var res = await SignService.SignAsync();
                LogMessage(res.ToString(), Level.Success);
            }
            catch (Exception ex)
            {
                LogMessage("发生异常， " + ex.Message, Level.Fail);
            }

            _lastRun = DateTime.Now;
            _dbContext.SubmitChanges();
            NotifyComplete();
        }

        private void UpdateTile(string message)
        {
            var appTile = ShellTile.ActiveTiles.First();
            if (appTile != null)
            {
                var data = new StandardTileData()
                {
                    Title = "快盘签到",
                    BackContent = message
                };
                appTile.Update(data);
            }

        }


        private void LogMessage(string message, int level = Level.Info)
        {
            var log = new Log() {Level = level, Message = message};
            _dbContext.Logs.InsertOnSubmit(log);
            UpdateTile(log.ToString());

        }

    }
}
